package jzbank.util;
import jzbank.common.exception.SyncException;
import jzbank.pojo.Person;
import java.io.*;

/**
 * 任务信息保存 序列化对象工具类
 */
public class SerializationUtil {
    // 序列化对象到文件
    public static void serializeObjectToFile(Object obj, String filePath)  {
        File file = new File(filePath);
        // 如果文件不存在，创建它
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new SyncException("文件序列化异常"+e.getMessage());
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(file);
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
            objectOutputStream.writeObject(obj);
        } catch (IOException e) {
            throw new SyncException("文件序列化异常"+e.getMessage());
        }
    }

    // 从文件反序列化对象
    public static Object deserializeObjectFromFile(String filePath) {
        File file = new File(filePath);
        // 如果文件不存在，创建它
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new SyncException("文件序列化异常"+e.getMessage());
            }
        }else {
            if (file.length()<1){
                return new Object(); // 返回 null 表示文件为空
            }
        }
        try (FileInputStream fileInputStream = new FileInputStream(file);
             ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
            return objectInputStream.readObject();
        } catch (IOException e) {
            throw new SyncException("文件序列化异常"+e.getMessage());
        } catch (ClassNotFoundException e) {
            throw new SyncException("文件序列化异常"+e.getMessage());
        }
    }
}